<template>
  <view class="tn-safe-area-inset-bottom">
    <!-- 导航栏 -->
    <u-navbar title="创圈子" :border="true" :autoBack="true" />
    <!-- 提示信息 -->
    <u-toast ref="uToast" />
    <!-- 加载动画 -->
    <u-loading-page :loading="loading" :iconSize="100" />
    <view class="tn-margin tn-bg-gray--light" style="border-radius: 10rpx;padding: 20rpx 30rpx;">
      <input v-model="name" maxlength="6" placeholder="请输入圈子名称" placeholder-style="color:#AAAAAA" />
    </view>
    <view class="tn-margin tn-bg-gray--light tn-padding" style="border-radius: 10rpx;">
      <textarea v-model="description" maxlength="100" placeholder="请输入圈子介绍" placeholder-style="color:#AAAAAA"></textarea>
    </view>
    <view class="tn-flex tn-flex-row-between tn-flex-col-center tn-padding-top-xl tn-margin">
      <view class="tn-flex justify-content-item">
        <view class="tn-text-center" style="border-radius: 100rpx;margin-right: 8rpx;width: 45rpx;height: 45rpx;line-height: 45rpx;">
          <text class="tn-icon-image tn-color-blue" style="font-size: 40rpx;"></text>
        </view>
        <view>
          <text class="tn-text-lg tn-padding-right-xs tn-text-bold">图片</text>
          <text class="tn-text-xs tn-padding-right-xs tn-color-grey">首张图片为头像</text>
        </view>
      </view>
      <view class="justify-content-item tn-text-df tn-color-grey" @tap="clearPic">
        <text class="tn-padding-xs">清空</text>
        <text class="tn-icon-delete"></text>
      </view>
    </view>
    <view class="tn-margin-left tn-padding-top-xs">
      <u-upload
        :capture="['album']"
		    :fileList="fileList"
        :maxCount="6"
        :multiple="true"
        :max-size="1024 * 1024 * 2"
		    @afterRead="afterRead"
		    @delete="deletePic"
	    />
    </view>

    <view class="tn-flex tn-flex-row-between tn-flex-col-center tn-padding-top-xl tn-margin">
      <view class="tn-flex justify-content-item">
        <view class="tn-text-center" style="border-radius: 100rpx;margin-right: 8rpx;width: 45rpx;height: 45rpx;line-height: 45rpx;">
          <text class="tn-icon-assort tn-color-blue" style="font-size: 40rpx;"></text>
        </view>
        <view class="tn-text-lg tn-padding-right-xs tn-text-bold">分类</view>
      </view>
    </view>

    <view class="tn-tag-content tn-margin tn-text-justify tn-padding-bottom">
      <view class="tag-box">
        <view class="tag-item" v-for="(item, index) in category" :key="index">
          <u-tag :text="`#${item.name}`" shape="circle" :plain="!item.checked" :type="item.type?item.type:'default'" :name="item.id" @click="checkboxTag" />
        </view>
      </view>
    </view>

    <!-- 悬浮按钮-->
    <view class="tn-flex tn-footerfixed">
      <view class="tn-flex-1 justify-content-item tn-margin-sm tn-text-center">
        <tn-button backgroundColor="#00FFC6" padding="40rpx 0" width="60%" shadow fontBold @click="create">
          <text class="tn-color-black">创 建</text>
        </tn-button>
      </view>
    </view>
    <view class='tn-tabbar-height'></view>
  </view>
</template>

<script>
import { getDict, cosToken, createCircle } from '@/api'
export default {
  name: 'create',
  data() {
    return {
      loading: true,
      fileList: [],
      name: '',
      description: '',
      category: [],
      tags: [],
    }
  },
  onLoad() {
    this.getDict();
  },
  methods: {
    // 获取字典
    async getDict() {
      const { code, message, data } = await getDict({ types: 'category' });
      if (code !== 1000) {
        return this.$refs.uToast.show({
          type: 'error',
          message: message
        });
      }
      this.loading = false;
      this.category = data['category'];
    },

    // 创建圈子
    async create() {
      const { name, description, tags, fileList } = this;
      if (!name) {
        return this.$refs.uToast.show({
          type: 'error',
          message: '请输入圈子名称'
        });
      }
      if (!description) {
        return this.$refs.uToast.show({
          type: 'error',
          message: '请输入圈子介绍'
        });
      }
      if (!fileList.length) {
        return this.$refs.uToast.show({
          type: 'error',
          message: '请上传圈子图片'
        });
      }
      if (!tags.length) {
        return this.$refs.uToast.show({
          type: 'error',
          message: '请选择圈子分类'
        });
      }
      const token = await cosToken();
      if (token.code !== 1000) {
        return this.$refs.uToast.show({
          type: 'error',
          message: token.message
        });
      }
      const images = await uni.$u.uploadFile(fileList, token.data);
      const { code, message, data } = await createCircle({ name, description, categoryIds: tags, images });
      if (code !== 1000) {
        return this.$refs.uToast.show({
          type: 'error',
          message: message
        });
      }
      this.$refs.uToast.show({
        type: 'success',
        message: message
      });
      const timer = setTimeout(() => {
        clearTimeout(timer);
        uni.navigateBack();
      }, 1000);
    },

    // 选择标签
    checkboxTag(e) {
      const types = ['primary', 'success', 'warning', 'error'];
      const index = Math.floor(Math.random() * types.length);
      this.category = this.category.map(item => {
        if (item.id === e && !item.checked) {
          if (this.tags.length < 3) {
            item.checked = true;
            item.type = types[index];
            this.tags.push(e);
          } else {
            this.$refs.uToast.show({
              type: 'error',
              message: '最多选择3个标签'
            });
          }
        } else if (item.id === e && item.checked) {
          item.checked = false;
          item.type = 'default';
          this.tags = this.tags.filter(item => item !== e);
        }
        return item;
      });
    },
    
    // 读取图片
    afterRead(e) {
      // 如果fileList有数据，追加数据，否则直接赋值
      if (this.fileList.length) {
        this.fileList = this.fileList.concat(e.file);
      } else {
        this.fileList = e.file;
      }
    },

    // 删除图片
    deletePic(e) {
      const that = this;
      uni.showModal({
        title: '温馨提示',
        content: '是否删除该图片',
        success: function (res) {
          if (res.confirm) {
            that.fileList = that.fileList.filter((item, i) => i !== e.index);
          }
        }
      });
    },
    
    // 清空图片
    clearPic() {
      this.fileList = [];
    }
  }
}
</script>

<style lang="scss" scoped>
.tag-box {
  text-align: start;
  .tag-item {
    display: inline-block;
    margin: 3rpx
  }
}
.tn-tabbar-height {
  min-height: 100rpx;
  height: calc(120rpx + env(safe-area-inset-bottom) / 2);
}

.tn-footerfixed {
  position: fixed;
  width: 100%;
  bottom: calc(30rpx + env(safe-area-inset-bottom));
  z-index: 98;
  box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0);

}

.tn-tag-content {
  &__item {
    display: inline-block;
    line-height: 45rpx;
    padding: 10rpx 30rpx;
    margin: 20rpx 20rpx 5rpx 0rpx;

    &--prefix {
      padding-right: 10rpx;
    }
  }
}
</style>